package com.bto.leasetest.response;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.bto.leasetest.utils.DateUtils;
import com.bto.leasetest.utils.IdUtils;
import com.bto.leasetest.utils.LogUtils;
import com.bto.leasetest.utils.NullUtils;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@Slf4j
@NoArgsConstructor
public class ResponseBase {
    private List<Map<String, Object>> body;
    private ResponseHead head;

    public static ResponseBase ok() {
        return restResult(null, "S", "成功", "");
    }

    public static ResponseBase ok(String businessKey) {
        return restResult(null, "S", "成功", businessKey);
    }

    public static ResponseBase ok(Map<String, Object> map) {
        return restResult(map, "S", "成功", "");
    }

    public static ResponseBase ok(Map<String, Object> map, String businessKey) {
        return restResult(map, "S", "成功", businessKey);
    }

    public static ResponseBase ok(Map<String, Object> map, String message, String businessKey) {
        return restResult(map, "S", message, businessKey);
    }

    public static ResponseBase fail(Map<String, Object> map, String type, String message, String businessKey) {
        return restResult(map, type, message, businessKey);
    }

    private static ResponseBase restResult(Map<String, Object> map, String type, String message, String businessKey) {
        ResponseBase result = new ResponseBase();
        if (NullUtils.isNull(map)) {
            map = new HashMap<>();
        }
        map.put("type", type);
        map.put("message", message);
        if (StringUtils.isBlank(businessKey)) {
            businessKey = IdUtils.fastSimpleUUID();
        }
        map.put("businessKey", businessKey);
        List<Map<String, Object>> resultGody = new ArrayList<>();
        resultGody.add(map);

        ResponseHead responseHead = new ResponseHead();
        responseHead.setSerialNumber(IdUtils.fastSimpleUUID());
        responseHead.setSystemId("YX-GDBT");
        responseHead.setTransactionCode("YX_FINANCE_PROJECT_OL_STATUS_SEND_SIT");
        responseHead.setTransactionTime(DateUtils.dateTimeNow("yyyyMMdd HH:mm:ss"));
        responseHead.setVersion(1);
        responseHead.setErrorMessage(message);
        if ("E".equals(type) || "R".equals(type)) {
            responseHead.setErrorCode("02");
        } else if ("S".equals(type)) {
            responseHead.setErrorCode("01");
        }

        result.setHead(responseHead);
        result.setBody(resultGody);
        log.info("result = " + result);
        LogUtils.requsetLogger.info("result Args   : {}", JSON.toJSONString(result, JSONWriter.Feature.PrettyFormat));
        return result;
    }
}
